<?php
/**
 * Created by : PhpStorm
 * User: 阿城 <479468212@qq.com>
 * Date: 2019/12/27
 * Time: 15:02
 */
namespace app\admin\middleware;

use app\admin\model\AdminMenu;
use app\admin\model\AdminUserAction;
use think\facade\Request;
use app\util\ReturnCode;

class AdminLog {

    /**
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return \think\response\Json
     */
    public function handle($request, \Closure $next) {
        $userInfo = $request->USER_INFO;
        $path = app('http')->getName().config('route.pathinfo_depr').Request::controller().config('route.pathinfo_depr').Request::action();
        $menuInfo = AdminMenu::where(['url' => $path])->find();
        if ($menuInfo) {
            $menuInfo = $menuInfo->toArray();
        } else {
            if($path == 'admin/Menu/generate'){
                return $next($request);
            }
            return json([
                'code' => ReturnCode::SYSTEM_ERROR,
                'msg'  => '当前路由未定义：' . $path,
                'data' => []
            ]);
        }
        AdminUserAction::create([
            'action_name' => $menuInfo['title'],
            'uid'         => $userInfo['id'],
            'nickname'    => $userInfo['nickname'],
            'add_time'    => time(),
            'url'         => $path,
            'data'        => json_encode($request->param())
        ]);
        return $next($request);
    }

}
